package com.baseframe.system.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baseframe.mybatis.utils.PageInfo;
import com.baseframe.mybatis.utils.PageUtil;
import com.baseframe.system.entity.BaseDict;
import com.baseframe.system.entity.request.BaseDictRequest;
import com.baseframe.system.entity.vo.BaseDictVO;
import com.baseframe.system.service.BaseDictService;
import com.baseframe.system.mapper.BaseDictMapper;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.function.Function;

/**

* @description 针对表【base_dict(字典表)】的数据库操作Service实现
* @createDate 2023-07-01 21:13:12
*/
@Service
public class BaseDictServiceImpl extends ServiceImpl<BaseDictMapper, BaseDict>
    implements BaseDictService{

    @Override
    public Page<BaseDictVO> getDictPage(PageInfo pageInfo, BaseDictRequest request) {
        Page<BaseDictVO> baseDictVOPage = PageUtil.buildPage(pageInfo, BaseDictVO.class);
        Page<BaseDictVO> resultPage = this.baseMapper.getParentVoPage(baseDictVOPage, request);

        getNodes(resultPage.getRecords(),(parent)->this.baseMapper.getChildNodes(parent));



        return resultPage;
    }


    @Override
    public BaseDictVO loadDictByCode(String code) {

        BaseDictVO baseDictVO = this.baseMapper.loadDictByCode(code);

        List<BaseDictVO> childNodesByEnableStatus = this.baseMapper.getChildNodesByEnableStatus(baseDictVO.getId());

        getNodes(childNodesByEnableStatus,(parent)->this.baseMapper.getChildNodesByEnableStatus(parent));

        baseDictVO.setChildNode(childNodesByEnableStatus);

        return baseDictVO;
    }

    @Override
    public List<BaseDictVO> loadAll() {


        return this.baseMapper.loadAll();
    }

    private void getNodes(List<BaseDictVO> baseDictVOS, Function<Long,List<BaseDictVO>> function){
        if(baseDictVOS==null){
            return;
        }
        for (BaseDictVO baseDictVO : baseDictVOS) {
            List<BaseDictVO> childNodes = function.apply(baseDictVO.getId());
            baseDictVO.setChildNode(childNodes);
            baseDictVO.setStatusName(baseDictVO.getStatus()==1?"启用":"封存");
            baseDictVO.setHaseChild(childNodes!=null&&childNodes.size()>0);
            getNodes(childNodes,function);
        }
    }
}




